﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using Common;
using Model.Other;

namespace Controllers.Filter
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ExceptionAttribute : FilterAttribute, IExceptionFilter//Controllers过滤器
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled==false)//未处理异常
            {
                IOHelper.WriteLog(filterContext.Exception);
                if (filterContext.HttpContext.Request.IsAjaxRequest())//ajax异步请求
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "Error"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    RouteValueDictionary dic = new RouteValueDictionary();
                    dic.Add("controller", "Error");
                    dic.Add("action", "Page404");
                    filterContext.Result = new RedirectToRouteResult("Default", dic);
                }

                filterContext.ExceptionHandled = true;
            }
        }
    }

}
